<template>
  <el-container class="forum-container">
    <el-header>
      <ForumHeader 
        :user="user" 
        :currentTab="currentTab" 
        :searchKey="searchKey" 
        :showUserMenu="showUserMenu"
        @update:currentTab="currentTab = $event"
        @update:searchKey="searchKey = $event"
        @update:showUserMenu="showUserMenu = $event"
      />
    </el-header>
    <el-container class="main-content-container">
      <el-aside width="250px">
        <div class="sidebar-container">
          <Sidebar 
            :user="user" 
            :currentTab="currentTab" 
            :categories="categories" 
            :qaCategories="qaCategories" 
            :activeCategory="activeCategory" 
            :activeQaCategory="activeQaCategory"
            @update:activeCategory="activeCategory = $event"
            @update:activeQaCategory="activeQaCategory = $event"
          />
        </div>
      </el-aside>
      <el-main>
        <el-card class="main-content-card" shadow="never">
          <el-tabs v-model="homeActiveTab" class="demo-tabs" @tab-click="handleTabClick">
            <el-tab-pane v-for="tab in homeTabs" :key="tab" :label="tab" :name="tab">
              <!-- {{ tab }} -->
            </el-tab-pane>
          </el-tabs>
          <ContentArea 
            :currentTab="currentTab" 
            :homeTabs="homeTabs" 
            :homeActiveTab="homeActiveTab" 
            :feedList="feedList" 
            :qaList="qaList" 
            :courseList="courseList" 
            :qaCategories="qaCategories" 
            :activeQaCategory="activeQaCategory"
          />
        </el-card>
      </el-main>
      <el-aside width="250px">
        <div class="right-sidebar-wrapper">
          <RightSidebar 
       
            :notices="notices" 
            :hotRank="hotRank"
          />
        </div>
      </el-aside>
    </el-container>
    <CreateDialog 
      :showCreateDialog="showCreateDialog" 
      :categories="categories" 
      :qaCategories="qaCategories"
      @update:showCreateDialog="showCreateDialog = $event"
    />
  </el-container>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import ForumHeader from '../components/ForumHeader.vue'
import Sidebar from '../components/Sidebar.vue'
import ContentArea from '../components/ContentArea.vue'
import RightSidebar from '../components/RightSidebar.vue'
import CreateDialog from '../components/CreateDialog.vue'

const router = useRouter()

  type UserInfo = {
    username: string;
    avatar: string;
    rank: number;
    id: number;
    };
  // 响应式数据
  const user = ref<UserInfo>({ username: '', avatar: '', rank: 0, id: 0 })
  // 修改 currentTab 的类型定义，将 "activity" 替换为 "follow" 
  const currentTab = ref<'home' | 'qa' | 'course' | 'follow' | 'live'>('home')
  const searchKey = ref('')
  const showUserMenu = ref(false)
  const headerHeight = ref(60) // 控制布局高度
  const loading = ref(true) // 加载状态

  // 分类数据
  // 定义分类项类型
  type Category = { id: number; name: string }
  
  // 分类数据，添加类型定义
  const categories = ref<Category[]>([])
  const qaCategories = ref<Category[]>([])
  const activeCategory = ref(0)
  const activeQaCategory = ref(0)

  // 标签页数据
  const homeTabs = ref(['推荐', '最新', '精华'])
  const homeActiveTab = ref('推荐') // 修改默认值为 '推荐'

  // 内容数据
  // 定义 feed 项类型
  type FeedItem = { 
    id: number; 
    title: string; 
    author: string; 
    views: number; 
    comments: number; 
    likes: number; 
    tags: string[]; 
    desc: string; 
  }
  
  // 内容数据，添加类型定义
  const feedList = ref<FeedItem[]>([])
  const qaList = ref<Category[]>([])
  const courseList = ref([])

  // 右侧栏数据
  const notices = ref([])
  const hotRank = ref([])

  // 发布内容弹窗
  const showCreateDialog = ref(false)
  const createType = ref<'post' | 'qa' | 'course'>('post')
  const createTitle = ref('')
  const createContent = ref('')
  const createCategory = ref(0)

  // 计算属性：当前问答列表
  const currentQa = computed(() => {
    return qaList.value.filter(item => 
      item.category === qaCategories.value.find(cat => cat.id === activeQaCategory.value)?.name
    )
  })

  // 模拟数据
  const mockData = { 
    user: {
      username: 'testUser',
      avatar: 'https://example.com/avatar.png',
      rank: 5,
      id: 1
    },
    categories: [
      { id: 1, name: '分类1' },
      { id: 2, name: '分类2' }
    ],
    qaCategories: [
      { id: 1, name: '问答分类1' },
      { id: 2, name: '问答分类2' }
    ],
    feedList: [
      { 
        id: 1, 
        title: '示例动态1', 
        author: 'testUser1', 
        views: 10, 
        comments: 5, 
        likes: 3, 
        tags: ['推荐'], 
        desc: '这是第一个示例动态'
      },
      { 
        id: 2, 
        title: '示例动态2', 
        author: 'testUser2', 
        views: 20, 
        comments: 8, 
        likes: 6, 
        tags: ['最新'], 
        desc: '这是第二个示例动态'
      },
      { 
        id: 3, 
        title: '示例动态3', 
        author: 'testUser3', 
        views: 15, 
        comments: 7, 
        likes: 4, 
        tags: ['精华'], 
        desc: '这是第三个示例动态'
      }
    ],
    qaList: [
      { 
        id: 1, 
        title: '示例问题', 
        author: 'testUser', 
        views: 10, 
        answers: 0, 
        category: '问答分类1' 
      }
    ],
    courseList: [
      { 
        id: 1, 
        title: '示例课程', 
        teacher: 'testTeacher', 
        learners: 100, 
        rating: 4.5, 
        cover: 'https://example.com/course.png' 
      }
    ],
    notices: [
      { id: 1, title: '论坛公告1' },
      { id: 2, title: '论坛公告2' }
    ],
    hotRank: [
      { id: 1, title: '热门内容1', views: 100, type: '动态' },
      { id: 2, title: '热门内容2', views: 80, type: '问答' }
    ]
  };
  
  // 获取数据的方法
  const fetchData = async () => {
    try {
      loading.value = true
      // 使用模拟数据替换接口请求
      user.value = mockData.user;
      categories.value = mockData.categories;
      activeCategory.value = categories.value[0]?.id || 0;
      qaCategories.value = mockData.qaCategories;
      activeQaCategory.value = qaCategories.value[0]?.id || 0;
      feedList.value = mockData.feedList;
      qaList.value = mockData.qaList;
      courseList.value = mockData.courseList;
      notices.value = mockData.notices;
      hotRank.value = mockData.hotRank;
    } catch (error) {
      console.error('数据获取失败:', error)
      alert('数据获取失败，请刷新重试')
    } finally {
      loading.value = false
    }
  }

  // 方法：切换用户菜单
  const toggleUserMenu = () => {
    showUserMenu.value = !showUserMenu.value
  }

  // 方法：处理搜索
  const handleSearch = async () => {
    if (searchKey.value.trim()) {
      try {
        const res = await axios.get(`/api/search?key=${searchKey.value}`)
        // 处理搜索结果
        console.log('搜索结果:', res.data)
        router.push(`/search?key=${searchKey.value}`)
      } catch (error) {
        console.error('搜索失败:', error)
        alert('搜索失败，请重试')
      }
    }
  }

  // 方法：发布内容
  const handlePublish = async () => {
    if (!createTitle.value || !createContent.value) {
      alert('标题和内容不能为空')
      return
    }

    try {
      await axios.post('/api/create-content', {
        type: createType.value,
        title: createTitle.value,
        content: createContent.value,
        category: createCategory.value
      })
      alert('发布成功')
      showCreateDialog.value = false
      createTitle.value = ''
      createContent.value = ''
      await fetchData() // 刷新数据
    } catch (error) {
      console.error('发布失败:', error)
      alert('发布失败，请重试')
    }
  }

  // 方法：打开发布内容弹窗
  const openCreateDialog = () => {
    showCreateDialog.value = true
  }

  // 方法：页面跳转
  const goProfile = () => {
    router.push(`/profile/${user.value.id}`)
  }
  
  const goSetting = () => {
    router.push('/setting')
  }
  
  const goDetail = (id: number) => {
    router.push(`/post/${id}`)
  }
  
  const goQaDetail = (id: number) => {
    router.push(`/qa/${id}`)
  }
  
  const goCourseDetail = (id: number) => {
    router.push(`/course/${id}`)
  }
  
  const goNotice = (id: number) => {
    router.push(`/notice/${id}`)
  }
  
  const handleLogout = () => {
    // 退出登录逻辑
    console.log('退出登录')
    user.value = { username: '', avatar: '', rank: 0, id: 0 }
    router.push('/login')
  }
  
  // 初始化：获取数据
  onMounted(() => {
    fetchData()
  })

  // 方法：根据排名返回对应的背景颜色
  const getRankColor = (index: number) => { 
    const colors = ['#ff4d4f', '#faad14', '#52c41a'];
    return index < 3 ? colors[index] : '#d9d9d9';
  }

  // 标签页点击事件处理函数
  const handleTabClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab, event)
  }
</script>

<style scoped>
.forum-container {
  height: 100vh;
  width: 100vw; /* 宽度设置为 100vw 铺满屏幕 */
  margin: 0; /* 外边距设为 0 */
  padding: 0; /* 内边距设为 0 */
  overflow-x: hidden; /* 禁止水平滚动 */
}

.main-content-container {
  display: flex;
  background-color: #dee6f3; /* 新增：设置灰色背景 */
  overflow-x: hidden; /* 新增：禁止水平滚动 */
}

el-header {
  padding: 0;
  width: 100%; /* 头部宽度 100% */
  position: fixed; /* 固定页头位置 */
  top: 0; /* 页头位于顶部 */
  z-index: 1000; /* 确保页头显示在最上层 */
}

el-main {
  padding: 0; /* 主内容区内边距设为 0 */
  flex: 1;
  overflow-x: hidden; /* 主内容区禁止水平滚动 */
}

el-aside {
  flex-shrink: 0; /* 禁止侧边栏收缩 */
}

.main-content-card {
  background-color: #fff; /* 白色背景 */
  border-radius: 4px; /* 圆角 */
  margin: 0px 0px; /* 保证顶部边距和左右侧栏一致 */
  height: calc(100% - 40px); /* 调整高度计算 */
}

.sidebar-container {
  margin: 20px 0 20px 20px;
}

.right-sidebar-wrapper {
  margin: 20px 20px 20px 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>
